/**
 * JAVACC DEMO 1.0
 * @copy right apache company All rights reserved. 
 * @Package com.apache.rpc.util  
 */
package com.apache.rpc.util;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.apache.api.vo.ResultEntity;
import com.apache.database.constant.Validator;
import com.apache.exception.ServiceException;
import com.apache.rpc.client.ProtocolServiceClient;
import com.apache.rpc.entity.Protocol;

/**
 * description:  接口调用方式转换类
 * @author Hou Dayu 创建时间：2014-11-14  
 * @Copyright(c)2014:
 */
public class LoadRpcService {

	private Logger log = Logger.getLogger(LoadRpcService.class);
	private static LoadRpcService instance;

	public LoadRpcService() {
		instance = this;
	}

	public static LoadRpcService service() {
		return instance;
	}

	public void destroy() {
		instance = null;
	}

	/**
	 * description:  service调用方法
	 * @param beanId     调用实现的BeanId名称
	 * @param methodName 方法名或对应的KEY名
	 * @param respType   返回值类型（xml/json）
	 * @param params     方法所需要的参数
	 * @author Hou Dayu  
	 * @update 2014-11-14
	 */
	@SuppressWarnings("rawtypes")
	public ResultEntity doService(String beanId, String methodName, String respType, Map<String, Object> params,
			Class attrClass) {
		ResultEntity resultEntity = null;
		if (ToolsUtil.isNull(beanId) || ToolsUtil.isNull(methodName)) {
			resultEntity = getResultEntity("BeanId及方法代号为空");
			return resultEntity;
		}
		respType = ToolsUtil.isNull(respType, "xml");
		Protocol protocol = new Protocol();
		protocol.setBeanId(beanId);
		protocol.setRespType(respType);
		protocol.setReqFlag(methodName);
		if (params != null && params.size() > 0) {
			protocol.setParams(params);
		}
		//doMethodParams(protocol, params);
		try {
			String result = "";
			log.info("请求参数:" + protocol.toString());
			Object obj = ProtocolServiceClient.instance().doService(protocol);
			if (Validator.isEmpty(obj)) {
				resultEntity = getResultEntity("接口调用超时");
				return resultEntity;
			}
			if (obj instanceof ResultEntity) {
				return (ResultEntity) obj;
			} else {
				result = String.valueOf(obj);
				if (ToolsUtil.isNull(result)) {
					resultEntity = getResultEntity("接口调用超时");
					return resultEntity;
				}
				if ("json".equalsIgnoreCase(respType)) {
					resultEntity = ProtocolServiceClient.instance().jsonToBean(result, ResultEntity.class, attrClass);
				} else {
					resultEntity = ProtocolServiceClient.instance().xmlToBean(result, ResultEntity.class);
				}
			}
		} catch (ServiceException e) {
			log.error("执行远程调用接口出错", e);
			resultEntity = getResultEntity("执行远程调用接口出错:" + e.getMessage());
			log.error("请求参数:" + protocol.toString());
		}
		return resultEntity;
	}

	private void doMethodParams(Protocol protocol, Map<String, Object> params) {
		if (!ToolsUtil.isEmpty(params)) {
			// 对参数的封装，对于List<Map<String,String>>类型利用protocol.setParams(String,Object)方式；对于String类型
			// 利用protocol.setParams(String,String);
			if (params != null && params.size() > 0) {
				Set<Map.Entry<String, Object>> set = params.entrySet();
				Iterator<Map.Entry<String, Object>> itr = set.iterator();
				Object obj = null;
				while (itr.hasNext()) {
					Map.Entry<String, Object> entry = itr.next();
					obj = entry.getValue();
					if (obj instanceof List) {
						protocol.setParams(entry.getKey(), obj);
					} else if (obj instanceof String) {
						protocol.setParams(entry.getKey(), (String) obj);
					}
				}
			}
		}
	}

	private ResultEntity getResultEntity(String message) {
		ResultEntity resultEntity = new ResultEntity();
		resultEntity.setResult("false");
		resultEntity.setMessage(message);
		//resultEntity.setEntity("");
		return resultEntity;
	}
}
